package factory.proxy;

import factory.Configuration;
import factory.excutor.DefaultExcutor;
import lombok.extern.java.Log;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Log
public class MapperProxyFactory<T> implements InvocationHandler {
    private Class<T>  type;
    private Configuration configuration;
    private DefaultExcutor excutor;

    public MapperProxyFactory(Class<T>  type, Configuration configuration, DefaultExcutor excutor) {
        this.type = type;
        this.configuration = configuration;
        this.excutor = excutor;
    }

    @Override
    public T invoke(Object proxy, Method method, Object[] args){
        //执行 sql
        log.info("class : ," + type.getName());
        log.info("method : ," + method.getName());

        String naspaceId = type.getName() + "." + method.getName();
        Object object = excutor.excute(configuration.getMapperStatementMap().get(naspaceId), args);
        return (T) object;
    }

    public <T> T getProxy(){
        return (T) Proxy.newProxyInstance(type.getClassLoader(),new Class[]{type},this);
    }

}
